#include "userinfomodel.h"
UserInfoModel::UserInfoModel(QObject *parent)
     : QAbstractListModel(parent)
{
     QHash<int, QByteArray> roles;
     roles[IpRole] = "ip";
     roles[NameRole] = "name";
     setRoleNames(roles);
}

 void UserInfoModel::addUserInfo(const userInfo &userinfo)
 {
     beginInsertRows(QModelIndex(), rowCount(), rowCount());
     m_userInfos << userinfo;
     endInsertRows();
 }

 int UserInfoModel::rowCount(const QModelIndex & parent) const {
     return m_userInfos.count();
 }

 QVariant UserInfoModel::data(const QModelIndex & index, int role) const {
     if (index.row() < 0 || index.row() > m_userInfos.count())
         return QVariant();
     const userInfo &userinfo = m_userInfos[index.row()];
     if (role == IpRole)
         return userinfo.getIp();
     else if (role == NameRole)
         return userinfo.getName();
     return QVariant();
 }

 void UserInfoModel::clear()
 {

     if(m_userInfos.count()==0) return;
     beginRemoveRows(QModelIndex(), 0, rowCount()-1);
     m_userInfos.clear();
     endRemoveRows();
 }

 void UserInfoModel::copyFromList(const QList<userInfo> &list)
{
     if(list.count()==0) return;
     clear();
     beginInsertRows(QModelIndex(), 0, list.size()-1);
     for(int i=0,len=list.size();i<len;++i)
         m_userInfos<<list[i];
     endInsertRows();
 }

QString UserInfoModel::ipToName(QString ip)
{
    if(m_userInfos.count()==0) return QString();
    for(int i=0,len=m_userInfos.size();i<len;++i)
        if(m_userInfos[i].getIp()==ip)
            return m_userInfos[i].getName();
    return QString();
}
